<template>
  <div class="update">
    <el-upload
        class="upload-demo1"
        ref="upload"
        :multiple="true"
        action="#"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-change="onUploadChange"
        :file-list="fileList"
        :auto-upload="false">
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <el-upload
        class="upload-demo2"
        :drag="true"
        action=""
        :http-request="onUpload"
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <QiePian class="upload-demo3"></QiePian>
  </div>
</template>

<script>
import { SylUpload } from '@/api/updata/updata.js'
import SparkMD5 from "spark-md5";
import QiePian from "@/views/system/user/update/QiePian";
export default {
  name: "index",
  components: {QiePian},
  created() {
    // console.log('触发了')
  },
  data() {
    return {
      files: [],
      fileList: []
    };
  },
  methods: {
    async submitUpload() {
      let file = this.$refs.file.files[0];
      if (file.length === 0) return console.log('上传文件为空');
      // 基于base64格式
      let base64 = await new Promise((resolve,reject) => {
        let fileReader = new FileReader();
        fileReader.readAsDataURL(this.$refs.file.files[0]);// 通过这个转换为base64;
        fileReader.onload = () => {
          resolve(fileReader.result);
        }
      })
      console.log(base64)
      SylUpload({fileBase: base64, fileName: this.$refs.file.files[0].name});
      // 基于formData格式
      let formData = new FormData();
      formData.append('file',this.files)
      formData.append('fileName',this.files.name);
      console.log(formData);
      // SylUpload(formData);
      //基于formData，文件名由前端加密生成hash值
      let changeBuffer = await new Promise((resolve,reject) => {
        let fileReader = new FileReader();
        fileReader.readAsArrayBuffer(file);   //  转化为buffer格式
        fileReader.onload = () => {
          let buffer = fileReader.result;
          let spark = new SparkMD5.ArrayBuffer();   // 创建一个加密器
          spark.append(buffer);    //  对buffer格式加密
          let bufferHash =spark.end();   // 加密结果 这个通过内容生成的hash是通过内容生成的。所以图片一样的不会重复上传。
          let suffix = /\.([a-zA-Z0-9]+$)/.exec(file.name)[1];
          let filename = bufferHash + '.' + suffix
          resolve(filename)   // 557dfad94210e284e38d9638176a0d97.jpg
        }
      })
      console.log(changeBuffer)
      // 多文件上传
      console.log(this.files)
      this.files.forEach(item => {
        let formData = new FormData();
        formData.append('file', item);
        formData.append('fileName', item.name);
        //发送ajax请求
        // SylUpload(formData);
      })

    },
    handleRemove(file, fileList) {
      console.log(file.name);
      const filterFile = this.files.filter(item => item.name !== file.name )  //移除元素
      this.files = filterFile;
    },
    handlePreview(file) {
      // console.log(file);
    },
    onUploadChange(file) {
      // console.log(file)
      if (file.size > 1*1024*1024) {
        console.log('您上传的文件不能大于1MB');
        return;
      }
      this.files.push(file);
    },
    async onUpload(file) {
      let formData = new FormData();
      formData.append('file', file.file);
      formData.append('fileName', file.file.name);
      //发送ajax请求
      let awaitData = await SylUpload(formData).then(res => {
        if(res.code === 200){
          return Promise.resolve(res.data);
        }else {
          return Promise.reject(res.msg);
        }
      }).catch(err => {
        console.log('有文件上传失败！'+err)
      });
      Promise.all(awaitData).then(res => {   // 对多个promise结果做处理
        console.log('所有文件都上传成功了'+res);
      }).catch(err => {
        console.log('有文件上传失败！'+err)
      })
    }

  }
}
</script>

<style scoped>

.update {

}
.upload-demo1 {
  width: 300px;
  height: 182px;
  border: groove;
  float: left;
}
.upload-demo2 {
  margin-left: 20px;
  float: left;
}
.upload-demo3{
  margin-left: 20px;
  float: left;
}
</style>
